import { Food } from './Food'
import { ScorePanel } from './ScorePanel'
import { Snake } from './Snake'

export class GameControl {
    snake: Snake
    food: Food
    scorePanel: ScorePanel
    direction = '' // 按键方向
    isLive = true // 是否存活

    constructor() {
        this.snake = new Snake()
        this.food = new Food()
        this.scorePanel = new ScorePanel()

        this.init()
    }

    init() {
        // 绑定键盘事件
        document.addEventListener('keydown', this.keyDownHandler.bind(this))
        this.run()
    }

    keyDownHandler(event: KeyboardEvent) {
        // ArrowUp Up
        // ArrowDown Down
        // ArrowLeft Left
        // ArrowRight Right
        this.direction = event.key
    }

    run() {
        // 根据方向 改变蛇的位置
        let X = this.snake.X
        let Y = this.snake.Y

        switch (this.direction) {
            case "ArrowUp":
            case "Up":
                Y -= 10
                break;
            case "ArrowDown":
            case "Down":
                Y += 10
                break;
            case "ArrowLeft":
            case "Left":
                X -= 10
                break;
            case "ArrowRight":
            case "Right":
                X += 10
                break;
        }

        this.checkEat(X, Y)

        // 修改位置
        try {
            this.snake.X = X
            this.snake.Y = Y
        } catch (e: any) {
            console.log(e);
            
            alert('游戏结束！')
            this.isLive = false
        }

        this.isLive && setTimeout(this.run.bind(this), 300 - (this.scorePanel.level - 1) * 30)
    }

    checkEat(X: number, Y: number) {
        if (X === this.food.X && Y === this.food.Y) {
            this.food.change()
            this.scorePanel.addScore()
            this.snake.addBody()
        }
    }
}
